package com.example.demospringboot;

import java.sql.Time;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    private static volatile Integer counts = 18;

    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static CountDownLatch latch = new CountDownLatch(1);

    private static ScheduledExecutorService put = Executors.newScheduledThreadPool(1, r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setName("thread-put");
        return t;
    });

    private static ScheduledExecutorService get = Executors.newScheduledThreadPool(1, r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setName("thread-put");
        return t;
    });

    public static void main(String[] args) {
        put.scheduleWithFixedDelay(() -> {
            readWriteLock.writeLock().lock();
            try{
                System.out.println("put----之前的counts："+counts);
                counts = counts + 1;
                System.out.println("put----之后的counts："+counts);
            }finally {
                readWriteLock.writeLock().unlock();
            }
        },0,1, TimeUnit.MILLISECONDS);
        get.scheduleWithFixedDelay(() -> {
            readWriteLock.writeLock().lock();
            try{
                System.out.println("get----之前的counts："+counts);
                counts = counts -3;
                System.out.println("get----之后的counts："+counts);
                if (counts < 2) {
                    latch.countDown();
                }
            }finally {
                readWriteLock.writeLock().unlock();
            }
        },0,1, TimeUnit.MILLISECONDS);
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("完成");
    }

}
